#!/usr/bin/env python
# -*- coding:utf-8 -*-
import hashlib

import MySQLdb

from core.parser import BaseParser


class Parser(BaseParser):
    START_ARGS = (None, None)
    use_db = ['mysql_pool']
    URL = ''
    NAME = 'a10jqka_article'
    SQL = 'insert into a10jqka_article(url,title,title_md5,publish_time,content,tag) values(\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')'

    def run(self, url=None, title=None):
        if url is None:
            self.log.error('run|url is None')
            return

        try:
            ret, _ = self.http_get(url)
        except Exception as e:
            self.log.error('run|http_get error url->%s', url, exc_info=1)
            return

        xpath_list = ret.xpath('//div[contains(@class, \'info-fr\') and contains(@class, \'fr\')]/span/text()')
        if len(xpath_list) > 0:
            info_tag_text = xpath_list[0].strip()
            if u'中性' in info_tag_text:
                info_tag = 0
            elif u'利空' in info_tag_text:
                info_tag = -1
            elif u'利好' in info_tag_text:
                info_tag = 1
            else:
                info_tag = None
        else:
            info_tag = None

        if info_tag is None:
            self.log.warning('run|not find info_tag url->%s', url)
            return

        if title is None:
            xpath_list = ret.xpath('//h2[@class=\'main-title\']/text()')
            if len(xpath_list) > 0:
                title = xpath_list[0].strip()

        md5 = hashlib.md5()
        md5.update(title.encode('utf-8'))
        title_md5 = md5.hexdigest()

        content = ''
        xpath_list = ret.xpath('//div[contains(@class, \'main-text\') and contains(@class, \'atc-content\')]/p')
        for xpath_item in xpath_list:
            x = xpath_item.xpath('./text()')
            if len(x) > 0:
                content += x[0].strip()

        publish_time = ''
        xpath_list = ret.xpath(
            '//div[contains(@class,\'info-fl\') and contains(@class, \'fl\')]/span[@id=\'pubtime_baidu\']/text()')
        if len(xpath_list) > 0:
            publish_time = xpath_list[0].strip()

        conn = self.dbs_conn.get('mysql_pool').get_connect()
        cur = conn.cursor()
        sql_url = MySQLdb.escape_string(url.encode('utf-8'))
        sql_title = MySQLdb.escape_string(title.encode('utf-8'))
        sql_title_md5 = MySQLdb.escape_string(title_md5.encode('utf-8'))
        sql_publish_time = MySQLdb.escape_string(publish_time.encode('utf-8'))
        sql_content = MySQLdb.escape_string(content.encode('utf-8'))
        sql_tag = MySQLdb.escape_string(str(info_tag).encode('utf-8'))
        try:
            cur.execute(self.SQL % (sql_url, sql_title, sql_title_md5, sql_publish_time, sql_content, sql_tag))
            conn.commit()
        except Exception as e:
            self.log.error('run|db error url->%s', url, exc_info=1)
            conn.rollback()
        finally:
            if conn:
                conn.close()
